<template>
  <div class="os-charts"
       :id="id"
       :style="{
          width: typeof width === 'number' ? `${width}px` : width, 
          height: typeof height === 'number' ? `${height}px` : height, 
        }"
       @mouseenter="mouseEnter"
       @mouseleave="mouseLeave">
  </div>
</template>
<script lang="ts">
  import { defineComponent, nextTick, onUnmounted, ref } from 'vue'
  import * as echarts from 'echarts'

  export default defineComponent({
    name: 'os-charts',
    props: {
      id: {
        type: String,
        required: true,
      },
      refresh: {
        type: Boolean,
        default: false,
      },
      width: {
        type: [String, Number],
        default: 450,
      },
      height: {
        type: [String, Number],
        default: 200,
      },
      duration: {
        type: Number,
        default: 5000,
      },
    },
    setup(props) {
      const activeInterval = ref<any>(null)
      const option = ref<any>(null)

      const setOption = (obj: any): void => {
        const ele: any = document.getElementById(props.id)
        let canvasDom = echarts.getInstanceByDom(ele)
        if (!canvasDom) {
          // 如果图表未初始化，就进行初始化。
          canvasDom = echarts.init(ele)
        }
        if (canvasDom) {
          canvasDom.clear()
          canvasDom.setOption(obj)
          option.value = obj
        }
        addEventListener('resize', () => {
          canvasDom.resize()
          removeEventListener('resize', () => {})
        })
        mouseLeave()
      }

      const mouseEnter = () => {
        if (props.refresh) {
          clearInterval(activeInterval.value)
        }
      }
      const mouseLeave = () => {
        if (props.refresh) {
          activeInterval.value = setInterval(() => {
            const ele = document.getElementById(props.id)
            if (ele) {
              let canvasDom = echarts.getInstanceByDom(ele)
              if (canvasDom) {
                canvasDom.clear()
                canvasDom.setOption(option.value)
              }
            } else {
              clearInterval(activeInterval.value)
            }
          }, props.duration)
        }
      }

      onUnmounted(() => {
        if (activeInterval.value) {
          clearInterval(activeInterval.value)
        }
      })

      return {
        option,
        setOption,
        activeInterval,
        mouseEnter,
        mouseLeave,
      }
    },
  })
</script>
<style lang="scss" scoped>
  @include b(charts) {
    width: 100%;
    height: 100%;
    position: relative;
  }
</style>